import os
from openai import OpenAI
from tqdm import tqdm
import base64
import json

client = OpenAI(
    # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key="sk-xxx",
    api_key="sk-d609ab546f5d46b6b2e29847bafce86c",
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
# completion = client.chat.completions.create(
#     model="qwen-vl-plus",  # 此处以qwen-vl-plus为例，可按需更换模型名称。模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
#     messages=[{"role": "user","content": [
#             {"type": "text","text": "这是什么"},
#             {"type": "image_url",
#              "image_url": {"url": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"}}
#             ]}]
#     )
# print(completion.model_dump_json())

def process_image(file_path):
    """处理单张图片并返回结果"""
    with open(file_path, "rb") as f:
        image_data = f.read()
    image_base64 = base64.b64encode(image_data).decode("utf-8")
    messages = [
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {"url": f"data:image/png;base64,{image_base64}"},
                },
                {"type": "text", "text": "图中描绘的是什么内容?"}
            ]   
        }
    ]
    completion = client.chat.completions.create(
        model="qwen-vl-max",  
        messages = messages
    )
    return completion.choices[0].message.content


def main():
    INPUT_FOLDER = "/home/chuanchang/毕设/TKY/downloaded_multimodal_data"

    # with open('missing_files.json', 'r', encoding='utf-8') as file:
    #     img_info = json.load(file)

    # img_name_list = []
    defeat_name_list = []
    # for key, value in img_info.items():
    #     img_name_list.append(key)

    # print("len", len(img_name_list))

    image_files = [f for f in os.listdir(INPUT_FOLDER) 
                   if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif'))]
    
    data = {}
    for file_name in tqdm(image_files, desc="Processing images"):
        file_path = os.path.join(INPUT_FOLDER, file_name)
        try:
            result_data = process_image(file_path)
            data[file_name] = result_data
        except:
            defeat_name_list.append(file_name)

        with open('poi_image_TKY.json', 'w', encoding='utf-8') as f1:
            json.dump(data, f1, ensure_ascii=False, indent=4)
    
    with open('poi_image_all_TKY.json', 'w', encoding='utf-8') as f2:
        json.dump(data, f2, ensure_ascii=False, indent=4)

    with open('poi_defeat_image_TKY.json', 'w', encoding='utf-8') as f3:
        json.dump(defeat_name_list, f3, ensure_ascii=False, indent=4)

    print("All images processed successfully!")

if __name__ == "__main__":
    main()





















































# import os
# from openai import OpenAI
# from tqdm import tqdm
# import base64
# import json

# client = OpenAI(
#     # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key="sk-xxx",
#     api_key="sk-d609ab546f5d46b6b2e29847bafce86c",
#     base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
# )
# # completion = client.chat.completions.create(
# #     model="qwen-vl-plus",  # 此处以qwen-vl-plus为例，可按需更换模型名称。模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
# #     messages=[{"role": "user","content": [
# #             {"type": "text","text": "这是什么"},
# #             {"type": "image_url",
# #              "image_url": {"url": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"}}
# #             ]}]
# #     )
# # print(completion.model_dump_json())

# def process_image(file_path):
#     """处理单张图片并返回结果"""
#     with open(file_path, "rb") as f:
#         image_data = f.read()
#     image_base64 = base64.b64encode(image_data).decode("utf-8")
#     messages = [
#         {
#             "role": "user",
#             "content": [
#                 {
#                     "type": "image_url",
#                     "image_url": {"url": f"data:image/png;base64,{image_base64}"},
#                 },
#                 {"type": "text", "text": "图中描绘的是什么内容?"}
#             ]   
#         }
#     ]
#     completion = client.chat.completions.create(
#         model="qwen-vl-max",  
#         messages = messages
#     )
#     return completion.choices[0].message.content


# def main():
#     INPUT_FOLDER = "/home/chuanchang/毕设/downloaded_multimodal_data"

#     with open('poi_image.json', 'r', encoding='utf-8') as file:
#         img_info = json.load(file)

#     img_name_list = []
#     defeat_name_list = []
#     for key, value in img_info.items():
#         img_name_list.append(key)

#     print("len", len(img_name_list))

#     image_files = [f for f in os.listdir(INPUT_FOLDER) 
#                    if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif'))]
    
#     data = img_info
#     for file_name in tqdm(image_files, desc="Processing images"):
#         if file_name in img_name_list:
#             continue
        
#         file_path = os.path.join(INPUT_FOLDER, file_name)
#         try:
#             result_data = process_image(file_path)
#             data[file_name] = result_data
#         except:
#             defeat_name_list.append(file_name)

#         with open('poi_image.json', 'w', encoding='utf-8') as f1:
#             json.dump(data, f1, ensure_ascii=False, indent=4)
    
#     with open('poi_image.json', 'w', encoding='utf-8') as f2:
#         json.dump(data, f2, ensure_ascii=False, indent=4)

#     with open('poi_defeat_image.json', 'w', encoding='utf-8') as f3:
#         json.dump(defeat_name_list, f3, ensure_ascii=False, indent=4)

#     print("All images processed successfully!")

# if __name__ == "__main__":
#     main()